package bma.common.netty.proxy;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.ChannelHandler;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.socket.ClientSocketChannelFactory;

import bma.common.langutil.io.HostPort;

public class ProxyHandlerSimple extends ProxyHandler {

	private ClientSocketChannelFactory channelFactory;
	private HostPort remote;

	public ProxyHandlerSimple(ClientSocketChannelFactory cf, HostPort remote) {
		super();
		this.channelFactory = cf;
		this.remote = remote;
	}

	public ClientSocketChannelFactory getChannelFactory() {
		return channelFactory;
	}

	public void setChannelFactory(ClientSocketChannelFactory channelFactory) {
		this.channelFactory = channelFactory;
	}

	public HostPort getRemote() {
		return remote;
	}

	public void setRemote(HostPort remote) {
		this.remote = remote;
	}

	@Override
	protected ClientBootstrap getRemoteBootstrap(ChannelHandlerContext ctx,
			ChannelStateEvent e, ChannelHandler handler) throws Exception {
		if (channelFactory == null)
			throw new NullPointerException("channelFactory");
		if (remote == null)
			throw new NullPointerException("remote");
		ClientBootstrap cb = new ClientBootstrap(channelFactory);
		cb.getPipeline().addLast("handler", handler);
		cb.setOption("remoteAddress", remote.createInetSocketAddress());
		return cb;
	}

	@Override
	protected String proxyTitle() {
		return remote == null ? super.toString() : "Proxy[" + remote + "]";
	}

}
